package com.cy.cy2025.util

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.cy.cy2025.MyApplication
import com.cy.cy2025.util.PermissionUtil.mPermissionsCallback

/**
 * 动态权限获取工具
 */
object PermissionUtil {


    var mPermissionsCallback: PermissionsCallback? = null

    fun checkSelfPermissions(vararg permissions: String): Boolean {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    MyApplication.app,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

    fun requestPermissions(
        permissionsCallback: PermissionsCallback,
        vararg permissions: String,
    ) {
        if (permissions.isEmpty() || mPermissionsCallback != null) return


        if (checkSelfPermissions(*permissions)) {
            permissionsCallback.onSuccess()
        } else {
            mPermissionsCallback = permissionsCallback
            PermissionsActivity.start(permissions.toList().toTypedArray())
        }

    }

}


interface PermissionsCallback {
    fun onSuccess()
    fun onFailure(failures: List<String>, forbiddings: List<String>)

}


class PermissionsActivity : AppCompatActivity() {

    companion object {
        fun start(permissions: Array<String>) {
            MyApplication.app.startActivity(
                Intent(
                    MyApplication.app,
                    PermissionsActivity::class.java
                ).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .putExtra("permissions", permissions)
            )
        }
    }

    private lateinit var permissionLauncher: ActivityResultLauncher<Array<String>>

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        // 确保Activity不会显示在最近任务列表中
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)

        val permissions = intent.getStringArrayExtra("permissions")
        if (permissions != null) {

            permissionLauncher = registerForActivityResult(
                ActivityResultContracts.RequestMultiplePermissions()
            ) {
                val failures = it.filter { !it.value }.map { it.key }.toList()
                if (failures.isEmpty()) {
                    mPermissionsCallback?.onSuccess()
                } else {
                    //被禁止的权限列表
                    val forbiddings = failures.filter { !ActivityCompat.shouldShowRequestPermissionRationale(this,it) }.toList()
                    mPermissionsCallback?.onFailure(failures,forbiddings)
                }
                finish()
            }
            permissionLauncher.launch(permissions)
        } else {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mPermissionsCallback = null
    }
}